package cc.smarnet.caihou;

import android.Manifest;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.smart.command.EscCommand;
import com.smart.command.LabelCommand;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

import cc.smarnet.caihou.adapter.FlowerClassesAdapter;
import cc.smarnet.caihou.adapter.FlowerPoleAdapter;
import cc.smarnet.caihou.adapter.PackingSpecificationsAdapter;
import cc.smarnet.caihou.bluetooth.BluetoothDeviceList;

import cc.smarnet.caihou.bluetooth.Constant;
import cc.smarnet.caihou.bluetooth.DeviceConnFactoryManager;
import cc.smarnet.caihou.bluetooth.ThreadPool;
import cc.smarnet.caihou.bluetooth.Utils;
import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 蓝牙连接的测试页面
 */
public class PrintTagActivity extends AppCompatActivity {
    private ImageButton imageButton;
    private Button cancelButton;
    private Spinner plantingPlaceSpinner;// 产地
    private Spinner plantingVarietySpinner;// 品种
    private Spinner plantingSorterSpinner;// 分拣员
    private TextView packingPeopleTextView;// 包装员
    private TextView sorterDateTextView;// 分拣日期
    private GridView packingSpecificationsGridView;
    private GridView flowerPoleGridView;
    private GridView flowerClassesGridView;// 等级
    private ImageView tagQuantityReduce;// 标签数量加
    private EditText tagQuantityEditText;// 标签数量
    private ImageView tagQuantityAdd;//标签数量减

    private final String basePlacePath = "/flower/plantingBase/getAllBase";// 获取基地的url
    private final String greenhouseUrl = "/flower/flowerPlantingGreenhouse/queryByParentId/";// 获取大棚的url
    private final String getvarietyNamesUrl = "/flower/flowerVariety/queryNames";// 获取品种的url
    private final String getPackUrl = "/flower/flowerVariety/queryPacksByName";// 获取规格的url
    private final String getLengUrl = "/flower/flowerVariety/queryLengthByName";// 获取品种单位的url，根据名称、规格
    private final String getClassesUrl = "/flower/flowerVariety/queryClassesByName";// 获取等级url，根据名称、规格
    private final String getHouseVarveryByIDUrl = "/flower/flowerPlantingGreenhouse/queryById";// 根据地块id查询地块关联的 品种信息
    private final String basePath = "/sys/api/getDictItems";

    private String token = "";
    private List<String> plantingPlaceList = new ArrayList<>();
    private List<String> plantingPlaceIDList = new ArrayList<>();
    private List<String> plantingVarietyList = new ArrayList<>();
    private List<String> plantingSorterList = new ArrayList<>();
    private List<String> plantingSorterIDList = new ArrayList<>();
    private List<String> plantingSorterVarveryList = new ArrayList<>();//大棚关联的品种列表
    private List<String> flowerClassesList = new ArrayList<>();
    private List<String> packingSpecificationsList = new ArrayList<>();
    private List<String> flowerPoleList = new ArrayList<>();

    private JSONArray varietyJSONArray; //品种的JSONArray

    private JSONArray packingSpecificationsJSONArray; //打包规格的JSONArray
    private JSONArray flowerPoleJSONArray; //花杆长度的JSONArray
    private JSONArray flowerClassesJSONArray; //花杆等级的JSONArray
    private String plantingPlace;// 产地
    private String plantingPlaceId;// 产地
    private String plantingVariety;// 品种
    private String plantingSorter;// 分拣员
    private String packingPeople;// 包装员

    private String sorterDate;// 分拣日期
    private String packingSpecifications;// 打包规格
    private String classes = "";// 等级
    private int tagQuantity = 1;// 标签数量
    private String flowerPole;// 单位


    private PackingSpecificationsAdapter packingSpecificationsAdapter;
    private FlowerPoleAdapter flowerPoleAdapter;
    private FlowerClassesAdapter flowerClassesAdapter;

    // 以下的值为调获取id接口时所需要的参数
    private String varietyValue;// 品种的值
    private String sorterValue;// 分拣员的值---大棚id
    private String packingSpecificationsValue;// 打包规格的值
    private String flowerPoleValue;// 花杆单位的值
    private String sourceURL = IPConfig.sourceURL;// 溯源码地址

    //蓝牙相关定义：
    private static final String TAG = "PrintTagActivity";
    ArrayList<String> per = new ArrayList<>();

    private int counts;
    private static final int REQUEST_CODE = 0x004;

    private Bitmap bitmap = Bitmap.createBitmap(660, 40, Bitmap.Config.ARGB_8888);

    /**
     * Connection status disconnected
     */
    private static final int CONN_STATE_DISCONN = 0x007;
    /**
     * Use printer command error
     */
    private static final int PRINTER_COMMAND_ERROR = 0x008;

    private static final int CONN_MOST_DEVICES = 0x11;
    private static final int CONN_PRINTER = 0x12;
    private PendingIntent mPermissionIntent;
    private String[] permissions = {
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.BLUETOOTH
    };
    private String usbName;
    private TextView tvConnState;
    private ThreadPool threadPool;

    private int id = 0;
    private int printcount = 0;
    private boolean continuityprint = false;

    // private KeepConn keepConn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e(TAG, "正式进入标签打印页面====2222222222=====");
        setContentView(R.layout.activity_flower_print);
        getSupportActionBar().hide();//隐藏标题栏


        tvConnState = (TextView) findViewById(R.id.client_printer_button);
        imageButton = findViewById(R.id.deliver_add_return);
        cancelButton = findViewById(R.id.cancel_button);
        plantingPlaceSpinner = findViewById(R.id.planting_place_spinner);
        plantingVarietySpinner = findViewById(R.id.planting_variety_spinner);
        plantingSorterSpinner = findViewById(R.id.planting_sorter_spinner);
        packingPeopleTextView = findViewById(R.id.packing_people_textView);
        sorterDateTextView = findViewById(R.id.sorter_date_textView);
        flowerClassesGridView = findViewById(R.id.flower_classes_GridView);
        packingSpecificationsGridView = findViewById(R.id.packing_specifications_GridView);
        flowerPoleGridView = findViewById(R.id.flower_pole_GridView);
        tagQuantityReduce = findViewById(R.id.tag_quantity_reduce);
        tagQuantityEditText = findViewById(R.id.tag_quantity_editText);
        tagQuantityAdd = findViewById(R.id.tag_quantity_add);


        checkPermission();
        requestPermission();
        tvConnState.setTextColor(Color.parseColor("red"));

        // 点击返回按钮的监听
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        // 点击取消按钮的监听
        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tagQuantityReduce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setTagQuantityReduce();
            }
        });
        tagQuantityAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setTagQuantityAdd();
            }
        });

        getPackingPeople();
        getSorterDate();

        TimerTask task = new TimerTask() {
            public void run() {
                getToken();
                getPlantingPlace();
//                getPlantingVariety();

                getSourceURL();


            }
        };
        Timer timer = new Timer();
        //1秒后执行
        timer.schedule(task, 1500);


    }

    public void getToken() {
        SharedPreferences sp = getSharedPreferences("userInfo", MODE_PRIVATE);
        token = sp.getString("token", null);
    }

    // 获取溯源码地址
    public void getSourceURL() {
//         "/planting_SourceURL"
        String url = IPConfig.baseUrl + basePath;
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .addHeader("X-TIMESTAMP", String.valueOf(Calendar.getInstance().getTimeInMillis()))
                .addHeader("X-Sign", String.valueOf(Calendar.getInstance().getTimeInMillis()))
                .addParams("dictCode", "planting_SourceURL")
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(PrintTagActivity.this, "Token失效，请重新登录", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(PrintTagActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        JSONArray objects = JSON.parseArray(response);
                        if (objects.size() > 0) {
                            JSONObject jsonObject = objects.getJSONObject(0);
                            sourceURL = jsonObject.getString("title");
                            if (StringUtils.isBlank(sourceURL)) {
                                sourceURL = IPConfig.sourceURL;
                            }
                        }
                    }
                });
    }

    // 获取基地
    public void getPlantingPlace() {
//        String url = IPConfig.baseUrl + placePath;
        String url = IPConfig.baseUrl + basePlacePath;
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(PrintTagActivity.this, "Token失效，请重新登录", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(PrintTagActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            JSONArray jsonArray = JSON.parseArray(result);

                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject jsonObj = jsonArray.getJSONObject(i);
                                String place = jsonObj.getString("name");
                                plantingPlaceList.add(place);
                                plantingPlaceIDList.add(jsonObj.getString("id"));
                            }
                            plantingPlaceSpinner();
//                            getGreenhouseByPd (plantingPlaceIDList.get(0));
                        }
                    }
                });
    }

    // 获取大棚----改为大棚下拉选择
    public void getGreenhouseByPd(String id) {
        plantingSorterList.clear();
        plantingSorterIDList.clear();
        if (StringUtils.isBlank(id)) {
            return;
        }
        String url = IPConfig.baseUrl + greenhouseUrl + id;
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
                .addParams("parentId", id)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(PrintTagActivity.this, "Token失效，请重新登录", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(PrintTagActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            JSONArray jsonArray = JSON.parseArray(result);

                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject jsonObj = jsonArray.getJSONObject(i);
                                String place = jsonObj.getString("name");
//                                plantingPlaceList.add(place);
//                                plantingPlaceIDList.add(jsonObj.getString("id"));
                                plantingSorterList.add(place);
                                plantingSorterIDList.add(jsonObj.getString("id"));
                            }
                            plantingSorterSpinner();
                        }
                    }
                });
    }

    // 获取品种
    public void getPlantingVariety() {
        String url = IPConfig.baseUrl + getvarietyNamesUrl;
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(PrintTagActivity.this, "Token失效，请重新登录", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(PrintTagActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            varietyJSONArray = JSON.parseArray(result);

                            for (int i = 0; i < varietyJSONArray.size(); i++) {
                                JSONObject jsonObj = varietyJSONArray.getJSONObject(i);
                                String plantingVariety = jsonObj.getString("name");
                                plantingVarietyList.add(plantingVariety);
                            }
                            plantingVarietySpinner();

                        }
                    }
                });
    }

    // 获取包装员
    public void getPackingPeople() {
        SharedPreferences sp = getSharedPreferences("userInfo", MODE_PRIVATE);
        String userInfo = sp.getString("userInfo", null);
        packingPeople = JSON.parseObject(userInfo).getString("realname");
        packingPeopleTextView.setText(packingPeople);
    }

    // 获取分拣日期
    public void getSorterDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(System.currentTimeMillis());
        sorterDate = sdf.format(date);
        sorterDateTextView.setText(sorterDate);
    }


    // 获取打包规格
    public void getPackingSpecifications(String name) {
        String url = IPConfig.baseUrl + getPackUrl;
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
                .addParams("name", name)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(PrintTagActivity.this, "Token失效，请重新登录", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(PrintTagActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            packingSpecificationsJSONArray = JSON.parseArray(result);
                            packingSpecificationsList.clear();
                            for (int i = 0; i < packingSpecificationsJSONArray.size(); i++) {
                                JSONObject jsonObj = packingSpecificationsJSONArray.getJSONObject(i);
                                String packingSpecifications = jsonObj.getString("packingSpecifications");
                                packingSpecificationsList.add(packingSpecifications);
                            }
                            if (packingSpecificationsList.size() > 0) {
                                packingSpecifications = packingSpecificationsList.get(0);// 默认打包规格的值为packingSpecificationsList的第一个值
                                packingSpecificationsValue = packingSpecifications;
                                getClasses(varietyValue, packingSpecificationsValue);
                            }

                            packingSpecificationsAdapter = new PackingSpecificationsAdapter(PrintTagActivity.this, packingSpecificationsList);
                            packingSpecificationsGridView.setAdapter(packingSpecificationsAdapter);
                            packingSpecificationsGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                    packingSpecifications = packingSpecificationsList.get(position);
                                    packingSpecificationsValue = packingSpecifications;
                                    packingSpecificationsAdapter.setSelection(position);
                                    packingSpecificationsAdapter.notifyDataSetChanged();

                                    getClasses(varietyValue, packingSpecificationsValue);
                                }
                            });
                        }
                    }
                });
    }

    // 获取等级
    public void getClasses(String name, String packingPeople) {
        String url = IPConfig.baseUrl + getClassesUrl;
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
                .addParams("name", name)
                .addParams("packing", packingPeople)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(PrintTagActivity.this, "Token失效，请重新登录", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(PrintTagActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            flowerClassesJSONArray = JSON.parseArray(result);
                            flowerClassesList.clear();

                            for (int i = 0; i < flowerClassesJSONArray.size(); i++) {
                                JSONObject jsonObj = flowerClassesJSONArray.getJSONObject(i);
                                String classes = jsonObj.getString("classes");
                                flowerClassesList.add(classes);
                            }
                            classes = flowerClassesList.get(0);// 默认花杆长度的值为flowerPoleList的第一个值
                            getFlowerPole(varietyValue, packingSpecificationsValue, classes);

                            flowerClassesAdapter = new FlowerClassesAdapter(PrintTagActivity.this, flowerClassesList);
                            flowerClassesGridView.setAdapter(flowerClassesAdapter);
                            flowerClassesGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                    classes = flowerClassesList.get(position);
                                    flowerClassesAdapter.setSelection(position);
                                    flowerClassesAdapter.notifyDataSetChanged();

                                    getFlowerPole(varietyValue, packingSpecificationsValue, classes);
                                }
                            });
                        }
                    }
                });
    }

    // 获取单位
    public void getFlowerPole(String name, String packingPeople, String classes2) {
        String url = IPConfig.baseUrl + getLengUrl;
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
                .addParams("name", name)
                .addParams("packing", packingPeople)
                .addParams("classes", classes2)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(PrintTagActivity.this, "Token失效，请重新登录", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(PrintTagActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            flowerPoleJSONArray = JSON.parseArray(result);
                            flowerPoleList.clear();
                            for (int i = 0; i < flowerPoleJSONArray.size(); i++) {
                                JSONObject jsonObj = flowerPoleJSONArray.getJSONObject(i);
                                String flowerPole = jsonObj.getString("flowerPoleLength");
                                flowerPoleList.add(flowerPole);
                            }
                            if (flowerPoleList.size() > 0) {
                                flowerPole = flowerPoleList.get(0);// 默认花杆长度的值为flowerPoleList的第一个值
                                flowerPoleValue = flowerPole;
                            }

                            flowerPoleAdapter = new FlowerPoleAdapter(PrintTagActivity.this, flowerPoleList);
                            flowerPoleGridView.setAdapter(flowerPoleAdapter);
                            flowerPoleGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                    flowerPole = flowerPoleList.get(position);
                                    flowerPoleValue = flowerPole;
                                    flowerPoleAdapter.setSelection(position);
                                    flowerPoleAdapter.notifyDataSetChanged();
                                }
                            });
                        }
                    }
                });
    }

    // 根据地块id查询品种信息。
    public void getVarverysByHouseID(String id) {
        plantingSorterVarveryList.clear();
        plantingVariety = ""; //清空以选择的品种
        varietyValue = "";//清空以选择的品种
        String url = IPConfig.baseUrl + getHouseVarveryByIDUrl;
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
                .addParams("id", id)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(PrintTagActivity.this, "Token失效，请重新登录", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(PrintTagActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            JSONObject objects = JSONObject.parseObject(result);
                            String varietys = objects.getString("variety");
                            if (StringUtils.isNotBlank(varietys)) {
                                String[] split = varietys.split(",");
                                plantingSorterVarveryList = new ArrayList<>(Arrays.asList(split));
                                plantingVarietySpinner();
                            }
                        }
                    }
                });
    }

    //产地的spinner ===改为了基地下拉
    public void plantingPlaceSpinner() {
        ArrayAdapter placeArrayAdapter = new ArrayAdapter(this, R.layout.my_spinner_item, plantingPlaceList);
        placeArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        plantingPlaceSpinner.setAdapter(placeArrayAdapter);
        plantingPlaceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                plantingPlace = plantingPlaceList.get(i);
                plantingPlaceId = plantingPlaceIDList.get(i);
                plantingSorterList.clear();
                plantingSorterIDList.clear();
                plantingSorter = "";
                sorterValue = "";
                getGreenhouseByPd(plantingPlaceId);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    //品种的spinner
    public void plantingVarietySpinner() {
//        ArrayAdapter plantingVarietyArrayAdapter = new ArrayAdapter(this, R.layout.my_spinner_item, plantingVarietyList);
        //改为从地块中获取品种列表，不再冲数据库获取
        ArrayAdapter plantingVarietyArrayAdapter = new ArrayAdapter(this, R.layout.my_spinner_item, plantingSorterVarveryList);
        plantingVarietyArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        plantingVarietySpinner.setAdapter(plantingVarietyArrayAdapter);
        plantingVarietySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//                plantingVariety = plantingVarietyList.get(i);
                plantingVariety = plantingSorterVarveryList.get(i);
                varietyValue = plantingVariety;
                getPackingSpecifications(varietyValue);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    //分拣员的spinner===改为了大棚下拉
    public void plantingSorterSpinner() {
        ArrayAdapter plantingSorterArrayAdapter = new ArrayAdapter(this, R.layout.my_spinner_item, plantingSorterList);
        plantingSorterArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        plantingSorterSpinner.setAdapter(plantingSorterArrayAdapter);
        plantingSorterSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                plantingSorter = plantingSorterList.get(i);
                sorterValue = plantingSorterIDList.get(i);
                getVarverysByHouseID(sorterValue);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    // 标签数量减
    public void setTagQuantityReduce() {
        if (tagQuantityEditText.getText().equals("") || tagQuantityEditText.getText().length() <= 0) {
            tagQuantityEditText.setText("1");
        } else {
            tagQuantity = Integer.parseInt(tagQuantityEditText.getText().toString());
            tagQuantity -= 1;
            if (tagQuantity < 1) {
                tagQuantity = 1;
                tagQuantityEditText.setText("1");
            } else {
                tagQuantityEditText.setText(String.valueOf(tagQuantity));
            }
        }
    }

    // 标签数量加
    public void setTagQuantityAdd() {
        if (tagQuantityEditText.getText().equals("") || tagQuantityEditText.getText().length() <= 0) {
            tagQuantityEditText.setText("1");
        } else {
            tagQuantity = Integer.parseInt(tagQuantityEditText.getText().toString());
            tagQuantityEditText.setText(String.valueOf(++tagQuantity));
        }
    }


    /**
     * Print label  打印标签
     */
    public void btnLabelPrint(View view) {
        Integer text = Integer.parseInt(tagQuantityEditText.getText().toString());
        if (text == null || text <= 0) {
            text = 1;
        }
        for (int i = 0; i < text; i++) {
            threadPool = ThreadPool.getInstantiation();
            threadPool.addTask(() -> {
                if (!isConnected()) {
                    mHandler.obtainMessage(CONN_PRINTER).sendToTarget();
                    return;
                }
                getId();
            });
        }
    }

    public void getId() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTime = df.format(new Date());
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("baseName", plantingPlace);
        map.put("flowerPoleLength", flowerPoleValue);
        map.put("packer", packingPeople);
        map.put("packingSpecifications", packingSpecificationsValue);
        map.put("sortTime", nowTime);
        map.put("sorter", sorterValue);
        map.put("classes", classes);
        map.put("sourceBase", plantingPlaceId);//基地id
        map.put("sourceGreenhouse", sorterValue);//大棚id
        map.put("tagNum", tagQuantity);
        map.put("variety", varietyValue);
        String requestJsonString = JSON.toJSONString(map);
        String url = IPConfig.baseUrl + "/flower/flowerTagPrint/add";
        OkHttpUtils
                .postString()
                .addHeader("X-Access-Token", token)
                .url(url)
                .content(requestJsonString)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            String responseId = JSON.parseObject(result).getString("id");
                            sendLabel(responseId);
                        }
                    }
                });
    }


    @Override
    protected void onStart() {
        super.onStart();
        IntentFilter filter = new IntentFilter();
        filter.addAction(DeviceConnFactoryManager.ACTION_QUERY_PRINTER_STATE);
        filter.addAction(DeviceConnFactoryManager.ACTION_CONN_STATE);
        registerReceiver(receiver22, filter);
    }

    private void checkPermission() {
        for (String permission : permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, permission)) {
                per.add(permission);
            }
        }
    }

    private void requestPermission() {
        if (per.size() > 0) {
            String[] p = new String[per.size()];
            ActivityCompat.requestPermissions(this, per.toArray(p), REQUEST_CODE);
        }
    }

    /**
     * Bluetooth connect
     */
    public void btnBluetoothConn(View view) {
        startActivityForResult(new Intent(this, BluetoothDeviceList.class), Constant.BLUETOOTH_REQUEST_CODE);
    }

    /**
     * Disconnect
     */
    public void btnDisConn(View view) {
        if (!isConnected()) {
            Utils.toast(this, getString(R.string.str_cann_printer));
            return;
        }
        mHandler.obtainMessage(CONN_STATE_DISCONN).sendToTarget();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {

                case Constant.BLUETOOTH_REQUEST_CODE: {
                    closeport();
                    //Get bluetoot mac address
                    String macAddress = data.getStringExtra(BluetoothDeviceList.EXTRA_DEVICE_ADDRESS);
                    //Init DeviceConnFactoryManager
                    new DeviceConnFactoryManager.Build()
                            .setConnectMethod(DeviceConnFactoryManager.CONN_METHOD.BLUETOOTH)
                            //Set bluetooth mac address
                            .setMacAddress(macAddress)
                            .build();
                    //Open port
                    threadPool = ThreadPool.getInstantiation();
                    threadPool.addTask(() -> DeviceConnFactoryManager.getDeviceConnFactoryManager().openPort());

                    break;
                }
                default:
                    break;
            }
        }
    }


    /**
     * Print label
     */
    void sendLabel(String id) {
        LabelCommand tsc = new LabelCommand();
        // Set the label size according to the actual size
        tsc.addSize(80, 50);
        // Set the label gap according to the actual size. If it is no gap paper, set it to 0
        tsc.addGap(2);
        // Set print direction
        tsc.addDirection(LabelCommand.DIRECTION.BACKWARD, LabelCommand.MIRROR.NORMAL);
        // Turn on Printing with response for continuous printing
        tsc.addQueryPrinterStatus(LabelCommand.RESPONSE_MODE.ON);
        // Set origin coordinates
        tsc.addReference(0, 0);
        // Tearing mode on
        tsc.addTear(EscCommand.ENABLE.ON);
        // Clear print buffer
        tsc.addCls();
//         Draw simplified Chinese
//        tsc.addText(10, 0, LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE, LabelCommand.ROTATION.ROTATION_0, LabelCommand.FONTMUL.MUL_1, LabelCommand.FONTMUL.MUL_1,
//                "Welcome to use SMARNET printer");
//         Draw a picture
        Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.xdnylogo);
        tsc.addBitmap(5, 30, -1, 5.0f, LabelCommand.BITMAP_MODE.OVERWRITE, 340, b);

        tsc.addBar(5, 110, 350, 1);

        tsc.addText(20, 135, LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE, LabelCommand.ROTATION.ROTATION_0, LabelCommand.FONTMUL.MUL_1, LabelCommand.FONTMUL.MUL_1,
                "产品：" + plantingVariety);
        if (StringUtils.isBlank(plantingPlace)) {
            plantingPlace = "";
        }
        tsc.addText(20, 175, LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE, LabelCommand.ROTATION.ROTATION_0, LabelCommand.FONTMUL.MUL_1, LabelCommand.FONTMUL.MUL_1,
                "产地：" + plantingPlace + plantingSorter);
        tsc.addText(20, 210, LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE, LabelCommand.ROTATION.ROTATION_0, LabelCommand.FONTMUL.MUL_1, LabelCommand.FONTMUL.MUL_1,
                "规格：" + packingSpecifications + " · " + classes);

//        tsc.addText(200, 255, LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE, LabelCommand.ROTATION.ROTATION_0, LabelCommand.FONTMUL.MUL_1, LabelCommand.FONTMUL.MUL_1,
//                "包装员：" + packingPeople);
//        tsc.addText(200, 255, LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE, LabelCommand.ROTATION.ROTATION_0, LabelCommand.FONTMUL.MUL_1, LabelCommand.FONTMUL.MUL_1,
//                "单位：" + flowerPole );
        tsc.addText(230, 255, LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE, LabelCommand.ROTATION.ROTATION_0, LabelCommand.FONTMUL.MUL_1, LabelCommand.FONTMUL.MUL_1,
                "包装员：" + packingPeople);


        SimpleDateFormat dateFm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //格式化当前系统日期
        String dateTime = dateFm.format(new java.util.Date());
        tsc.addText(230, 300, LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE, LabelCommand.ROTATION.ROTATION_0, LabelCommand.FONTMUL.MUL_1, LabelCommand.FONTMUL.MUL_1,
                "时间：" + dateTime);
        tsc.addText(230, 355, LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE, LabelCommand.ROTATION.ROTATION_0, LabelCommand.FONTMUL.MUL_1, LabelCommand.FONTMUL.MUL_1,
                "云南省数字冷库管理系统");

        tsc.addQRCode(400, 40, LabelCommand.EEC.LEVEL_L, 6, LabelCommand.ROTATION.ROTATION_0, id);
        tsc.addText(335, 177, LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE, LabelCommand.ROTATION.ROTATION_0, LabelCommand.FONTMUL.MUL_1, LabelCommand.FONTMUL.MUL_1,
                id);

        tsc.addQRCode(30, 250, LabelCommand.EEC.LEVEL_L, 3, LabelCommand.ROTATION.ROTATION_0, sourceURL + "?sid=" + id);
        tsc.addText(10, 352, LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE, LabelCommand.ROTATION.ROTATION_0, LabelCommand.FONTMUL.MUL_1, LabelCommand.FONTMUL.MUL_1,
                "溯源扫一扫");

//        tsc.add1DBarcode(10, 250, LabelCommand.BARCODETYPE.CODE128, 100, LabelCommand.READABEL.EANBEL, LabelCommand.ROTATION.ROTATION_0, "SMARNET");
        // print label
        tsc.addPrint(1, 1);
        // Buzzer sounds after label printing
        tsc.addSound(2, 100);
        tsc.addCashdrwer(LabelCommand.FOOT.F5, 255, 255);
        Vector<Byte> datas = tsc.getCommand();
        // send data
        DeviceConnFactoryManager.getDeviceConnFactoryManager().sendDataImmediately(datas);
    }


    private BroadcastReceiver receiver22 = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case DeviceConnFactoryManager.ACTION_CONN_STATE:
                    int state = intent.getIntExtra(DeviceConnFactoryManager.STATE, -1);
                    int deviceId = intent.getIntExtra(DeviceConnFactoryManager.DEVICE_ID, -1);
                    switch (state) {
                        case DeviceConnFactoryManager.CONN_STATE_DISCONNECT:
                            if (id == deviceId) {
                                tvConnState.setText(getString(R.string.str_conn_state_disconnect));
                                tvConnState.setTextColor(Color.parseColor("red"));
                            }
                            break;
                        case DeviceConnFactoryManager.CONN_STATE_CONNECTING:
                            tvConnState.setText(getString(R.string.str_conn_state_connecting));
                            tvConnState.setTextColor(Color.parseColor("red"));
                            break;
                        case DeviceConnFactoryManager.CONN_STATE_CONNECTED:
                            tvConnState.setText(getString(R.string.str_conn_state_connected) + "\n" + getConnDeviceInfo());
                            tvConnState.setBackgroundColor(Color.parseColor("#CCFFCC"));
                            tvConnState.setTextColor(Color.parseColor("green"));
                            break;
                        case DeviceConnFactoryManager.CONN_STATE_FAILED:
                            Utils.toast(PrintTagActivity.this, getString(R.string.str_conn_fail));
                            //wificonn=false;
                            tvConnState.setText(getString(R.string.str_conn_state_disconnect));
                            tvConnState.setTextColor(Color.parseColor("red"));
                            break;
                        default:
                            break;
                    }
                    break;
                case DeviceConnFactoryManager.ACTION_QUERY_PRINTER_STATE:
                    if (counts >= 0) {
                        if (continuityprint) {
                            printcount++;
                            Utils.toast(PrintTagActivity.this, getString(R.string.str_continuityprinter) + " " + printcount);
                        }
                        if (counts != 0) {
//                            sendContinuityPrint();
                        } else {
                            continuityprint = false;
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * Reconnection recycles the last connected object to avoid memory leakage
     */
    private void closeport() {
        if (isConnected()) {
//            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].reader.cancel();
            DeviceConnFactoryManager.getDeviceConnFactoryManager().closePort();
        }
    }


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case CONN_STATE_DISCONN:
                    if (isConnected()) {
                        DeviceConnFactoryManager.getDeviceConnFactoryManager().closePort();
                        Utils.toast(PrintTagActivity.this, getString(R.string.str_disconnect_success));
                    }
                    break;
                case PRINTER_COMMAND_ERROR:
                    Utils.toast(PrintTagActivity.this, getString(R.string.str_choice_printer_command));
                    break;
                case CONN_PRINTER:
                    Utils.toast(PrintTagActivity.this, getString(R.string.str_cann_printer));
                    break;
            }
        }
    };

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(receiver22);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "离开页面了========");
//        if (isConnected()) {
//            DeviceConnFactoryManager.getDeviceConnFactoryManager().closePort();
//        }
//        if (threadPool != null) {
//            threadPool.stopThreadPool();
//        }
//        if (!isConnected()) {
//            Utils.toast(this, getString(R.string.str_cann_printer));
//            return;
//        }
        mHandler.obtainMessage(CONN_STATE_DISCONN).sendToTarget();
    }

    private String getConnDeviceInfo() {
        String str = "";
        if (isConnected()) {
            if (DeviceConnFactoryManager.getDeviceConnFactoryManager().getConnMethod() == DeviceConnFactoryManager.CONN_METHOD.BLUETOOTH) {
//                str += "BLUETOOTH\n";
                str += "名称: " + DeviceConnFactoryManager.getDeviceConnFactoryManager().getMacAddress();
            } else if (DeviceConnFactoryManager.getDeviceConnFactoryManager().getConnMethod() == DeviceConnFactoryManager.CONN_METHOD.WIFI) {
                str += "WIFI\n";
                str += "IP: " + DeviceConnFactoryManager.getDeviceConnFactoryManager().getIp() + "\n";
                str += "Port: " + DeviceConnFactoryManager.getDeviceConnFactoryManager().getPort();
            }
        }
        return str;
    }

    private boolean isConnected() {
        return DeviceConnFactoryManager.getDeviceConnFactoryManager() != null && DeviceConnFactoryManager.getDeviceConnFactoryManager().getConnState();
    }

}